<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @current-change="selectNode"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="space-beween">
          <el-col>
            <el-button size="mini" @click="sendMultiMessage">群发通知</el-button>
          </el-col>
          <el-col>
            <el-row type="flex" justify="end">
              <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
              <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
              <!-- <el-button size="mini" @click="exportEmployeeExcel">excel导出</el-button> -->
            </el-row>
          </el-col>
        </el-row>

        <!-- 表格组件 -->
        <el-table ref="employeeTable" row-key="id" :data="list" @select="selectChange" @select-all="selectChange">
          <el-table-column type="selection" />
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 导入员工弹层 -->
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @updateSuccess="getEmployeeList" />
    <!-- 角色弹层 -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 群发消息弹层 -->
    <el-dialog title="群发通知" :visible.sync="showMultiMessageDialog">
      <div class="select_users">
        <el-tag
          v-for="item in all_users"
          :key="item.id"
          closable
          @close="delSendUser(item)"
        >@{{ item.username }}</el-tag>
      </div>
      <el-form label-width="80px">
        <el-form-item label="消息等级">
          <el-select v-model="messageForm.type" size="mini">
            <el-option :value="1" label="通知消息" />
            <el-option :value="2" label="提示消息" />
            <el-option :value="3" label="重要消息" />
            <el-option :value="4" label="紧急消息" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input v-model="messageForm.content" type="textarea" :rows="4" place-holder="通知内容的长度在5-100个字符" />
        </el-form-item>
      </el-form>

      <!-- 群发通知 -->
      <template #footer>
        <el-row type="flex" justify="end">
          <el-button size="mini" @click="btnCancelSend">取消</el-button>
          <el-button size="mini" type="primary" @click="btnSend">发送通知</el-button>
        </el-row>
      </template>

    </el-dialog>

  </div>

</template>

<script>
import { getDepartmentList } from '@/api/department'
import { assignRole, delEmployee, exportEmployee, getEmployeeDetail, getEmployeeList, getEnableRoleList, sendMuchMessage } from '@/api/employee'
import { totree } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'

export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      // 群发消息弹层
      messageForm: {
        type: 1, // 1 通知消息 2 提示消息 3  重要消息 4 紧急消息
        content: ''
      },
      showMultiMessageDialog: false, // 群发消息弹层
      selectUsers: {}, // 存储每一页的用户 如  {1: [], 2: [], 3: [] ...}
      depts: [],
      list: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      total: 0,
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      showRoleDialog: false, // 控制角色的弹层显示和隐藏
      roleList: [], // 角色列表
      roleIds: [], // 选中的角色id列表
      currentUserId: null // 用来记录当前点击的用户id
    }
  },
  computed: {
    // 所有选中用户的数据
    all_users() {
      return [...Object.values(this.selectUsers).flat()]
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    // 取消-关闭弹层
    btnCancelSend() {
      this.showMultiMessageDialog = false
    },
    // 确定发送
    async btnSend() {
      if (!this.all_users.length) {
        return this.$message.warning('发送通知用户列表不能为空')
      }
      if (this.messageForm.content.length < 5 || this.messageForm.content.length > 100) {
        return this.$message.warning('通知的内容为5-100个字符之间')
      }
      await sendMuchMessage({
        userIds: this.all_users.map(item => item.id),
        ...this.messageForm
      })
      this.messageForm = {
        type: 1,
        content: ''
      }
      this.$message.success('群发消息成功')
      this.showMultiMessageDialog = false
    },
    // 删除要发送的用户
    delSendUser(obj) {
      Object.keys(this.selectUsers).forEach((key) => {
        const index = this.selectUsers[key].findIndex(item => item.id === obj.id)
        this.$refs.employeeTable.toggleRowSelection(obj, false) // 去掉选中行
        if (index > -1) {
          this.selectUsers[key].splice(index, 1)
        }
      })
      this.selectUsers = { ...this.selectUsers }
    },
    // 群发消息
    sendMultiMessage() {
      if (!this.all_users.length) {
        return this.$message.warning('请先选择要群发的员工')
      }
      this.showMultiMessageDialog = true
    },
    // 选择发生变化
    selectChange(selectRows) {
      // 去重
      this.selectUsers = {
        ...this.selectUsers,
        [this.queryParams.page]: selectRows
      }
    },
    // 获取部门列表
    async getDepts() {
      const res = await getDepartmentList()
      this.depts = totree(res, 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点   node-key="id"
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 切换树形节点时 选中节点
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 切换页码
    async changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      await this.getEmployeeList() // 查询数据
      // 切换页码处理选中的行数据 问题
      this.$refs.employeeTable.store.states.selection = this.selectUsers[this.queryParams.page] || []
      this.$refs.employeeTable.store.updateSelectionByRowKey() // 重新计算selection
      this.$refs.employeeTable.store.updateAllSelected() // 计算全选
    },
    // 改变查询条件
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出员工信息
    async exportEmployee() {
      const loading = this.$loading({
        lock: true,
        text: '正在导出...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 发送请求 - 导出员工列表
      const res = await exportEmployee()
      loading.close()
      // 基于bolb对象下载文件
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 删除员工方法
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true // 调整顺序
    },
    // 点击角色确定按钮
    async btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}

.select_users {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 10px;
  border: 1px solid #ccc;
  border-radius: 10px;
  span {
    margin: 6px 5px;
  }
}
</style>
